package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.PostsAuditVo;
import com.ruoyi.system.domain.vo.PostsCreateVo;
import com.ruoyi.system.dto.PostsDTO;
import com.ruoyi.system.dto.PostsStatisticsDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.PostsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 动态帖子业务实现
 *
 * 说明：
 * - 写操作开启事务，保证数据一致性
 * - DTO 转换中对 images/tags 进行逗号分隔解析，兼容前端数组展示
 */
@Service
public class PostsServiceImpl implements PostsService {
    @Autowired
    private PostsMapper postsMapper;
    @Autowired
    private PostMediaMapper postMediaMapper;
    @Autowired
    private PostLikeMapper postLikeMapper;
    @Autowired
    private PostCommentMapper postCommentMapper;
    @Autowired
    private PostRewardMapper postRewardMapper;

    /** 查询帖子详情（DTO） */
    @Override
    public PostsDTO selectPostsById(Long id) {
        Posts p = postsMapper.selectById(id);
        if (p == null) {
            throw new ServiceException("动态不存在");
        }
        return getData(p);
    }

    /** 查询帖子列表（DTO） */
    @Override
    public List<PostsDTO> selectPostsList(Posts posts) {
        List<Posts> list = postsMapper.selectList(new LambdaQueryWrapper<Posts>().orderByDesc(Posts::getCreatedAt));
        List<PostsDTO> dtos = new ArrayList<>();
        for (Posts p : list) {
            dtos.add(getData(p));
        }
        return dtos;
    }

    private PostsDTO getData(Posts p){
        PostsDTO dto = this.toDto(p);
        // 查询图片或者视频
        List<PostMedia> mediaList = postMediaMapper.selectList(new LambdaQueryWrapper<PostMedia>()
            .eq(PostMedia::getPostId, p.getId())
            .orderByAsc(PostMedia::getOrderIndex));
        if (mediaList != null && !mediaList.isEmpty()) {
            List<String> images = mediaList.stream()
                .map(PostMedia::getUrl)
                .collect(Collectors.toList());
            dto.setImages(images);
        }
        // 查询点赞数
        int likeCount = Math.toIntExact(postLikeMapper.selectCount(new LambdaQueryWrapper<PostLike>()
            .eq(PostLike::getPostId, p.getId())));
        dto.setLikeCount(likeCount);
        // 查询评论数
        int commentCount = Math.toIntExact(postCommentMapper.selectCount(new LambdaQueryWrapper<PostComment>()
            .eq(PostComment::getPostId, p.getId())));
        dto.setCommentCount(commentCount);
        // 查询打赏数
        int rewardCount = Math.toIntExact(postRewardMapper.selectCount(new LambdaQueryWrapper<PostReward>()
            .eq(PostReward::getPostId, p.getId())));
        dto.setRewardCount(rewardCount);
        return dto;
    }

    /** 查询帖子列表（实体） */
    @Override
    public List<Posts> selectPostsEntityList(Posts posts) {
        return postsMapper.selectPostsList(posts);
    }

    /** 新增帖子（默认置为待审核、非置顶） */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPosts(PostsCreateVo vo) {
        Posts posts = new Posts();
        BeanUtils.copyProperties(vo, posts);
        posts.setContentText(vo.getContent());
        if (posts.getStatus() == null) {
            posts.setStatus(3);
        }
        if (posts.getIsTop() == null) {
            posts.setIsTop(false);
        }
        posts.setCreatedAt(new Date());
        posts.setUpdatedAt(new Date());
        // 保存媒体数据
        List<String> images = vo.getImages();
        posts.setMediaType(vo.getMediaType());
        int i = postsMapper.insertPosts(posts);
        if (images != null && !images.isEmpty()) {
            int index = 0;
            for (String image : images) {
                PostMedia postMedia = new PostMedia();
                postMedia.setPostId(posts.getId());
                postMedia.setUrl(image);
                postMedia.setMediaType(vo.getMediaType().toString());
                postMedia.setOrderIndex(index);
                postMediaMapper.insert(postMedia);
                index++;
            }
        }
        return i;
    }

    /** 修改帖子（按需更新） */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePosts(Posts posts) {
        if (posts.getId() == null) {
            throw new ServiceException("ID不能为空");
        }
        posts.setUpdatedAt(new Date());
        return postsMapper.updatePosts(posts);
    }

    /** 删除单个帖子 */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePostsById(Long id) {
        return postsMapper.deletePostsById(id);
    }

    /** 批量删除帖子 */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePostsByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        return postsMapper.deletePostsByIds(ids);
    }

    /** 审核帖子（更新状态与原因） */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditPost(PostsAuditVo auditVo) {
        Posts p = postsMapper.selectPostsById(auditVo.getId());
        if (p == null) {
            throw new ServiceException("动态不存在");
        }
        p.setStatus(auditVo.getStatus());
        p.setAuditReason(auditVo.getAuditReason());
        p.setAuditStatus(Objects.equals(auditVo.getStatus(), 1) ? 1 : 0);
        p.setUpdatedAt(new Date());
        return postsMapper.updatePosts(p);
    }

    /** 获取统计数据（示例返回，可按需替换为真实统计） */
    @Override
    public PostsStatisticsDTO getStatistics() {
        PostsStatisticsDTO dto = new PostsStatisticsDTO();
        dto.setTotalPosts(0);
        dto.setTodayPosts(0);
        dto.setPendingReview(0);
        dto.setViolationPosts(0);
        return dto;
    }

    /** 将实体转换为 DTO（images/tags 按逗号分隔转换为数组） */
    private PostsDTO toDto(Posts p) {
        PostsDTO dto = new PostsDTO();
        dto.setId(p.getId());
        dto.setUserId(p.getUserId());
        dto.setUserName(p.getUserName());
        dto.setAvatar(p.getAvatar());
        dto.setContent(p.getContentText());
        dto.setTags(split(p.getTags()));
        dto.setVisibility(p.getVisibility());
        dto.setStatus(p.getStatus());
        dto.setLikeCount(p.getLikeCount());
        dto.setCommentCount(p.getCommentCount());
        dto.setShareCount(p.getShareCount());
        dto.setRewardAmount(p.getRewardAmount());
        dto.setIsTop(p.getIsTop());
        dto.setAuditStatus(p.getAuditStatus());
        dto.setAuditReason(p.getAuditReason());
        dto.setCreateTime(p.getCreatedAt());
        dto.setUpdateTime(p.getUpdatedAt());
        dto.setMediaType(p.getMediaType());
        return dto;
    }

    /** 字符串按逗号拆分为数组（去空白） */
    private List<String> split(String s) {
        if (s == null || s.trim().isEmpty()) return null;
        return Arrays.stream(s.split(","))
            .map(String::trim)
            .filter(x -> !x.isEmpty())
            .collect(Collectors.toList());
    }
}
